package models

import (
	auth "savor_gin/utils/bcryptUtils"
	"time"
)

type UserInfo struct {
	UserId        uint64    `gorm:"column:user_id;primary_key;auto_increment" json:"user_id"`
	UserName      string    `gorm:"column:user_name;not null" json:"user_name" binding:"required" `
	UserAge       uint8     `gorm:"column:user_age;" json:"user_age"`
	Password      string    `gorm:"column:password;not null" json:"password" binding:"required"`
	Email         string    `gorm:"column:email;not null" json:"email" binding:"required"`
	PhoneNumber   string    `gorm:"column:phone_number;" json:"phone_number"`
	UserStatus    int8      `gorm:"column:user_status;" json:"user_status"`
	LastLoginDate time.Time `gorm:"lastLoginDate" json:"last_login_date"`
	AvatarURL     string    `gorm:"column:avatar_url" json:"avatar_url"`
	CreatedAt     time.Time `gorm:"column:create_at;autoCreateTime" json:"create_at"`
}

func (u *UserInfo) TableName() string {
	return "user"
}
func (u *UserInfo) Delete() error {
	return DB.Self.Delete(&u).Error
}

// 修改  --- 修改那一行， 修改什么字段
func (u *UserInfo) Update() error {
	return DB.Self.Model(&u).Update(&u).Error
}

// 查询，提供Id查询

func GetUserInfoById(id uint64) (*UserInfo, error) {
	u := &UserInfo{}
	r := DB.Self.First(u, id) //根据主键，主键是整数类型去查询
	//r := DB.Self.Where("Id = ?", id).First(u)
	return u, r.Error
}

// 查询所有
func GetUser() ([]*UserInfo, error) {
	users := make([]*UserInfo, 0)
	err := DB.Self.Find(&users).Error
	return users, err
}

// 仿写模糊查询

func GetUserByLike(key string) ([]*UserInfo, error) {
	userList := make([]*UserInfo, 0)
	err := DB.Self.Where("user_name like ? ", "%"+key+"%").Find(&userList).Error
	return userList, err
}

// 注册
func (u *UserInfo) Create() error {
	return DB.Self.Create(&u).Error
}

// 密码加密
func (u *UserInfo) Encrypt() (err error) {
	u.Password, err = auth.Encrypt(u.Password)
	return err
}

// 注册前先校验
func (u *UserInfo) IsRegistered(name string) bool {
	var user UserInfo
	result := DB.Self.Where("user_name=?", name).First(&user)
	if result.Error != nil && !result.RecordNotFound() {
		return false
	}
	return result.RowsAffected > 0
}
func GetUserByName(name string) (*UserInfo, error) {
	u := &UserInfo{}
	r := DB.Self.Where("user_name = ?", name).First(&u)
	return u, r.Error
}

// 接收登录信息的结构体
type UserLogin struct {
	UserName string `json:"username" from:"username" binding:"required"`
	Password string `json:"password" from:"password" binding:"required"`
}
